package com.alu4r.atcrowdfunding.controller;

import com.alu4r.atcrowdfunding.bean.Member;
import com.alu4r.atcrowdfunding.bean.Permission;
import com.alu4r.atcrowdfunding.bean.User;

import com.alu4r.atcrowdfunding.manager.service.UserService;
import com.alu4r.atcrowdfunding.potal.service.MemberService;
import com.alu4r.atcrowdfunding.util.AjaxResult;
import com.alu4r.atcrowdfunding.util.Constant;
import com.alu4r.atcrowdfunding.util.JsonMessageResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class DispatcherController {

    @Autowired
    private UserService userService;

    @Autowired
    private MemberService memberSerice;

    @RequestMapping("/register")
    public String registerPage() {
        System.out.println("进入注册页");
        return "register";
    }

    @ResponseBody
    @RequestMapping(value = "doRegister", method = RequestMethod.POST)
    public Object register(String loginacct, String userpswd, String email) {
        User user = new User(null, loginacct, userpswd, loginacct, email, null);

        System.out.println("注册");
        AjaxResult ajaxResult = new AjaxResult();
        Boolean isInsertSuccess = userService.insertUserRegister(user);
        System.out.println("***********" + isInsertSuccess);
        ajaxResult.setSuccess(isInsertSuccess);
        return ajaxResult;
    }



    @RequestMapping("/main")
    public String main(HttpSession session) {

        System.out.println("进入主页面");

        return "main";
    }

    /**
     * 异步请求
     *
     * @param loginacct
     * @param userpswd
     * @param type
     * @param session
     * @return
     */


    @ResponseBody//结合 Jackson组件，将返回结果转换为字符串，将JSON串以流的方式返回给客户端
    @RequestMapping(value = {"/doLogin"}, method = RequestMethod.POST)
    public Object doLogin(String loginacct, String userpswd, String type, String remember,
                          HttpSession session, HttpServletResponse response) {
        AjaxResult ajaxResult = new AjaxResult();
        System.out.println("***********登录");
        try {
            Map<String, Object> maps = new HashMap<>();
            maps.put("loginacct", loginacct);
            maps.put("userpswd", DigestUtils.md5Hex(userpswd));//MD5加密，在maven中添加commons-lang3依赖
            maps.put("type", type);

            if ("member".equals(type)) {
                Member member = memberSerice.queryMemberLogin(maps);
                session.setAttribute(Constant.LOGIN_MEMBER, member);
                ajaxResult.setSuccess(true);

                if ("1".equals(remember)) {
                    String logincode = "\"loginacct=" + member.getLoginacct() + "&userpwd=" + member.getUserpswd() + "&logintype=member\"";
                    Cookie cookie = new Cookie("logincode", logincode);
                    cookie.setMaxAge(60 * 60 * 24 * 14);//设置cookie过期时间
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            } else if ("user".equals(type)) {
                User user = userService.queryUserlogin(maps);
                session.setAttribute(Constant.LOGIN_USER, user);
                ajaxResult.setSuccess(true);
                if ("1".equals(remember)) {
                    String logincode = "\"loginacct=" + user.getLoginacct() + "&userpwd=" + user.getUserpswd() + "&logintype=user\"";
                    Cookie cookie = new Cookie("logincode", logincode);
                    cookie.setMaxAge(60 * 60 * 24 * 14);//设置cookie过期时间
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
                //将user的许可权限放在session
                userPermissionToSession(user, session);

            } else {

            }
            ajaxResult.setData(type);
        } catch (Exception e) {
            ajaxResult.setMassage("登录失败");
            ajaxResult.setSuccess(false);
        }
        return ajaxResult;
    }

    @ResponseBody
    @RequestMapping("/autoLogin")
    public JsonMessageResult autoLogin(String loginacct, String userpswd, String type, HttpSession session) {
        System.out.println("自动登录");
        JsonMessageResult jsonMessageResult = null;
        Map<String, Object> maps = new HashMap<>();
        maps.put("loginacct", loginacct);
        maps.put("userpswd", userpswd);
        maps.put("type", type);
        if ("member".equals(type)) {
            Member member = memberSerice.queryMemberLogin(maps);
            jsonMessageResult = JsonMessageResult.success();
            session.setAttribute(Constant.LOGIN_MEMBER, member);
        } else if ("user".equals(type)) {
            User user = userService.queryUserlogin(maps);
            //将user的许可权限放在session
            userPermissionToSession(user, session);
            jsonMessageResult = JsonMessageResult.success();
            session.setAttribute(Constant.LOGIN_USER, user);
        } else {
            jsonMessageResult = JsonMessageResult.fail();
        }
        return jsonMessageResult;
    }

    @RequestMapping("/login")
    public String login() {
        System.out.println("跳转到login界面");
        return "login";
    }


    @RequestMapping("/index")
    public String index() {
        System.out.println("进入首页");
        return "index";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();//清理session对象
        return "redirect:login.htm";
    }


    /**
     * 将user的许可权限放在session中
     *
     * @param user
     * @param session
     */
    private void userPermissionToSession(User user, HttpSession session) {

        List<Permission> myPermissions = userService.getPermissionByUserId(user.getId());

        Permission permissionROOT = null;

        Map<Integer, Permission> map = new HashMap<>();

        //获取只能登录许可的uri
        Set<String> myUri = new HashSet<>();

        for (Permission permission : myPermissions) {
            map.put(permission.getId(), permission);
            myUri.add("/" + permission.getUrl());
        }
        //把myUri放在session中
        session.setAttribute(Constant.MY_URIS, myUri);
        for (Permission permission : myPermissions) {
            Permission child = permission;
            if (child.getPid() == null) {
                permissionROOT = permission;
            }
            if (map.get(permission.getPid()) != null) {
                Permission parent = map.get(child.getPid());
                parent.getChildren().add(child);
            }
        }
        session.setAttribute("permissionROOT", permissionROOT);
    }

}
